package customer

import (
	"context"
	"errors"
	"fmt"
	"github.com/google/wire"
	"sieve_admin_server_userpass/app/dao"
	"sieve_admin_server_userpass/app/dao/sieve_config"
	"sieve_admin_server_userpass/app/schema"
	serviceSys "sieve_admin_server_userpass/app/service/sys"
	"sieve_admin_server_userpass/lib/log"
	"sieve_admin_server_userpass/lib/mysql"
	"strconv"
	"time"
)

var (
	SieveConfigSet = wire.NewSet(wire.Struct(new(SieveConfigSrv), "*"))
)

type SieveConfigSrv struct {
	RoleSrv               *serviceSys.RoleSrv
	Trans                 *dao.Trans
	SieveSourceConfigRepo *dao.SieveSourceConfigRepo
}

func (a *SieveConfigSrv) Get(ctx context.Context, item map[string]interface{}) ([]interface{}, error) {

	//	var (
	//		querySQL = fmt.Sprintf(`
	//			SELECT
	//				*
	//			FROM
	//			    sieve_source_config
	//			WHERE
	//			    %v = '%v' AND %v = '%v' AND deleted = 0
	// `, "`name`", item["name"], "`alias`", item["alias"])
	//	)

	var (
		querySQL = fmt.Sprintf(`
			SELECT
				*
			FROM
			    sieve_source_config
			WHERE 
			    %v = '%v' AND deleted = 0
`, "`name`", item["name"])
	)

	fmt.Println(querySQL)
	return a.SieveSourceConfigRepo.QueryRaw(ctx, querySQL, sieve_config.SieveSourceConfig{})
}

func (a *SieveConfigSrv) Create(ctx context.Context, item map[string]interface{}, args ...interface{}) interface{} {

	respSources, err := a.Get(ctx, item)
	if err != nil {
		return err
	}

	for _, v := range respSources {
		vSource := v.(*sieve_config.SieveSourceConfig)
		if vSource.Name == item["name"] {
			return errors.New(fmt.Sprintf("已经存在相同的筛源配置'%v'", item["label"]))
		}
	}

	var (
		now = time.Now().Unix()
		def = map[string]interface{}{
			"create_at":  now,
			"updated_at": now,
		}
	)

	for k, v := range def {
		item[k] = v
	}

	rowsAffected, err := a.SieveSourceConfigRepo.Create(ctx, item)
	if err != nil {
		return err
	}
	id, _ := rowsAffected.LastInsertId()
	if len(args) == 1 {
		*args[0].(*int64) = id
	}
	return err
}

func (a *SieveConfigSrv) Query(ctx context.Context, reqArgs map[string]interface{}, p schema.PaginationParam, repKeys []string) interface{} {

	if _, ok := reqArgs["name"]; ok {
		ctx = context.WithValue(ctx,
			"condition", map[string]string{"name": "LIKE"},
		)

		reqArgs["name"] = "'%" + reqArgs["name"].(string) + "%'"
	}

	req, err := a.SieveSourceConfigRepo.Query(ctx, reqArgs, p, repKeys)
	if err != nil {
		return err
	}
	return req
}

func (a *SieveConfigSrv) Update(ctx context.Context, uid uint64, reqArgs map[string]interface{}) error {

	if uid == uint64(a.RoleSrv.GetAdminRole().ID) {
		return errors.New(fmt.Sprintf("管理员权限不可以被修改"))
	}

	var (
		now        = time.Now().Unix()
		updateKeys = map[string]interface{}{
			"updated_at": now,
			"alias":      reqArgs["alias"],
			"name":       reqArgs["name"],
			"default":    reqArgs["default"],
		}
		queryKeys = map[string]interface{}{
			"id": reqArgs["id"],
		}
	)

	// 切换为默认
	if v, ok := reqArgs["default"]; ok {
		if v.(uint64) == 1 {
			if err := a.Trans.TransactionTx(ctx, func(ctx context.Context, t *mysql.Tx) error {

				var (
					updateSQL = fmt.Sprintf(`
				UPDATE 
					sieve_source_config
				SET 
				    %v = 2
				WHERE %v = 1 AND deleted = 0
`, "`default`", "`default`")
				)

				if _, err := a.SieveSourceConfigRepo.ExecRaw(ctx, updateSQL); err != nil {
					return err
				}

				return a.SieveSourceConfigRepo.Update(ctx, map[string]interface{}{
					"default": 1,
				}, queryKeys)
			}); err != nil {
				log.Err(fmt.Sprintf("更新默认筛源失败:%+v", err))
			}
		}
	}

	delete(updateKeys, "default")
	return a.SieveSourceConfigRepo.Update(ctx, updateKeys, queryKeys)
}

func (a *SieveConfigSrv) Delete(ctx context.Context, reqArgs map[string]interface{}) interface{} {

	var (
		id, _ = strconv.ParseUint(fmt.Sprintf("%v", reqArgs["id"]), 10, 64)
	)

	return a.SieveSourceConfigRepo.SoftDelete(ctx, id)
}
